package li.buda.utils.flex.validator {
import flash.events.EventDispatcher;

import flash.events.IEventDispatcher;

import mx.core.IMXMLObject;
import mx.events.ValidationResultEvent;
import mx.utils.ObjectUtil;

public class Validator extends EventDispatcher implements IMXMLObject {
    public function Validator() {
        super();
    }

    /**
     * @private
     * Storage for source property
     */
    private var _source:IEventDispatcher;

    public function get source():IEventDispatcher {
        return _source;
    }

    public function set source(value:IEventDispatcher):void {
        if (_source != null) {
            removeSourceListeners();
        }
        _source = value;
        if (_source != null) {
            addSourceListeners();
        }
    }

    protected function addSourceListeners():void {
        _source.addEventListener(ValidationResultEvent.VALID, validationHandler);
        _source.addEventListener(ValidationResultEvent.INVALID, validationHandler);
    }

    protected function removeSourceListeners():void {
        _source.removeEventListener(ValidationResultEvent.VALID, validationHandler);
        _source.removeEventListener(ValidationResultEvent.INVALID, validationHandler);
    }

    /**
     * Handler for validation events dispatched from <code>source</code> object.
     * @param e validation event
     */
    private function validationHandler(e:ValidationResultEvent):void {
        if (ObjectUtil.stringCompare(property, e.field) == 0) {
            listener.dispatchEvent(e.clone());
        }
    }

    /**
     * @private
     * Storage for property property
     */
    private var _property:String;

    public function get property():String {
        return _property;
    }

    public function set property(value:String):void {
        _property = value;
    }

    /**
     * @private
     * Storage for validation listener
     */
    private var _listener:IEventDispatcher;

    public function get listener():IEventDispatcher {
        return _listener;
    }

    public function set listener(value:IEventDispatcher):void {
        _listener = value;
    }

    //---------------------
    // IMXMLObject implementation
    //---------------------

    /**
     * @private
     * Implementation of this method is required because of implementation of
     * <code>mx.core.IMXMLObject</code> interface.
     */
    public function initialized(document:Object, id:String):void {
    }


}
}